<template>
  <div class="chat-dialog">
    <el-dialog :visible.sync="dialogVisible" width='800px' :close-on-click-modal="false" :close-on-press-escape="false"
               @open="open" @close="onCloseDialog">
      <el-container>
        <el-header class="header" height="70px">
          <span style="float: left; font-size: 30px; color: #f0f0f0; line-height: 70px">
            Autumn 聊天室
            <i style="font-size: 35px" class="iconfont icon-liaotian"></i>
          </span>
        </el-header>
        <el-main class="main">
          <div class="chatPanel">
            <el-tabs tab-position="left" style="height: 500px;" @tab-click="chooseChatUserTab">
              <el-tab-pane v-for="(chatUser, index) in chatUserList" :key="index">
                <chat-tap slot="label" :user="chatUser"/>
              </el-tab-pane>
              <chat-panel :currentMessageList="currentMessageList" :currentChatUser="currentChatUser"/>
            </el-tabs>
          </div>
        </el-main>
        <el-footer class="footer" height="140px">
          <div class="input">
            <el-input :rows="3" v-model="input" type="textarea" placeholder="请输入内容" resize="none"
                      @keyup.enter.native="sendMessage"></el-input>
          </div>
          <div class="chat-button">
            <el-upload action="/api/storage/file" class="chat-left-button" :on-success="handleUploadSuccess">
              <el-button type="info" plain icon="el-icon-upload">发送文件</el-button>
            </el-upload>
            <el-button type="primary" plain class="chat-right-button" round icon="el-icon-mobile-phone"
                       @click="sendMessage">发送消息
            </el-button>
          </div>
        </el-footer>
      </el-container>
    </el-dialog>
  </div>
</template>

<script>
import ChatTap from './ChatTab'
import ChatPanel from './ChatPanel'

export default {
  name: 'ChatDialog',
  components: {
    ChatTap,
    ChatPanel
  },
  props: {
    visible: Boolean
  },
  watch: {
    visible () {
      this.dialogVisible = this.visible
    },
    dialogVisible () {
      this.$emit('update:visible', this.dialogVisible)
    },
    messageList () {
      this.updateCurrentMessageList()
      console.log('this.currentMessageList:', this.currentMessageList)
    }
  },
  data () {
    return {
      dialogVisible: false,
      value: '',
      currentChatUser: {},
      input: '',
      webSocket: null,
      chatUserList: [],
      messageList: [],
      currentMessageList: []
    }
  },
  methods: {
    updateCurrentMessageList () {
      this.currentMessageList = []
      console.log('this.currentChatUser.account:', this.currentChatUser.account)
      this.messageList.forEach(message => {
        console.log(message)
        console.log(message.msgFrom)
        console.log(message.msgTo)
        if (message.msgFrom === this.currentChatUser.account || message.msgTo === this.currentChatUser.account) {
          this.currentMessageList.push(message)
        }
      })
      console.log('updateCurrentMessageList:', this.currentMessageList)
    },
    chooseChatUserTab (tab) {
      this.currentChatUser = this.chatUserList[tab.index]
      this.updateCurrentMessageList()
      console.log('chooseChatUserTab:', this.currentMessageList)
    },
    getChatUserList () {
      this.$axios.get('/api/chat/chat-user')
        .then(response => {
          let result = response.data
          if (result.success) {
            this.chatUserList = result.data
            if (this.chatUserList.length !== 0) {
              this.currentChatUser = this.chatUserList[0]
              console.log('chatUserList:', this.chatUserList)
            }
            this.getWebSocketServer()
          } else {
            this.$message.error(result.msg)
          }
        })
    },
    getWebSocketServer () {
      this.$axios.get('/api/chat/server-info')
        .then(response => {
          let result = response.data
          if (result.success) {
            const webSocketServer = result.data.webSocketBaseUrl
            console.log('this.webSocketServer', webSocketServer)
            // 开启 WebSocket
            this.openWebSocket(webSocketServer)
          } else {
            this.$message.error(result.msg)
          }
        })
    },
    openWebSocket (webSocketServer) {
      let that = this
      const webSocketServerUrl = webSocketServer + '/' + this.$store.state.user.account
      this.webSocket = new WebSocket(webSocketServerUrl)
      // 建立连接
      this.webSocket.onopen = function () {
        console.log('ws.onopen')
      }
      // 接收消息
      this.webSocket.onmessage = event => {
        let message = JSON.parse(event.data)
        switch (message.msgType) {
          case -1: {
            this.$message.info(message.msgContent)
            break
          }
          case 0:
            break
          case 1: {
            message.msgContent = `给你发送了文件：[${message.msgContent}]，请到个人文件仓库查收！`
            break
          }
          default:
        }
        console.log(message)
        that.messageList.push(message)
        console.log('that.messageList:', that.messageList)
      }
      // 关闭连接
      this.webSocket.onclose = function (event) {
        console.log('ws.onclose')
      }
      // 发生异常
      this.webSocket.onerror = function (event) {
        console.log('ws.onerror')
      }
    },
    // 发送消息
    sendMessage () {
      let message = {
        msgFrom: this.$store.state.user.account,
        msgTo: this.currentChatUser.account,
        msgType: 0,
        msgContent: this.input
      }
      this.webSocket.send(JSON.stringify(message))
      this.messageList.push(message)
      this.input = null
    },
    open () {
      // 获取聊天用户列表，web-socket server 信息
      this.getChatUserList()
    },
    onCloseDialog () {
      this.webSocket.close()
    },
    handleUploadSuccess (res) {
      let data = res.data
      let fileName = data.name
      let filePath = data.path
      let message = {
        msgFrom: this.$store.state.user.account,
        msgTo: this.currentChatUser.account,
        msgType: 1,
        msgContent: fileName,
        msgAttach: filePath
      }
      this.webSocket.send(JSON.stringify(message))
      message.msgContent = `给你发送了文件：[${fileName}]，请到个人文件仓库查收！`
      this.messageList.push(message)
    }
  }
}
</script>

<style lang="stylus" scoped>
  div >>> .el-dialog__body, div >>> .el-dialog__header {
    padding: 0;
  }

  div >>> .el-tabs__item {
    height: 100px;
    text-align: left;
    line-height: 10px;
  }

  div >>> .el-tabs__item.is-left {
    text-align: left;
  }

  .header {
    background: #ffa879;
  }

  .main {
    border-bottom: 1px solid #eee;

    .chatPanel {
      height: 500px;
    }
  }

  .footer {
    .input {
      margin-top: 10px;
      margin-bottom: 5px;
      width: 100%;
      float: right;
      background: #f5f5c6;
    }

    .chat-button {
      text-align: left;
      width: 100%;

      .chat-left-button {
        float: left;
      }

      .chat-right-button {
        float: right;
      }
    }
  }
</style>
